from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """购物车序列化器"""
    sku_id = serializers.IntegerField(label='商品sku编号', min_value=1)
    count = serializers.IntegerField(label='商品数量', min_value=1)
    selected = serializers.BooleanField(label='勾选状态', default=True)

    def validate(self, attrs):

        sku_id = attrs['sku_id']
        count = attrs['count']

        # 1.验证商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        # 2.验证商品数量不低于商品库存数量
        if count > sku.stock:
            raise serializers.ValidationError('库存量不足')

        # 3.验证通过后,返回验证数据
        return attrs


class SKUCartSerializer(serializers.ModelSerializer):
    """购物车商品输出序列化器"""
    # 定义新增输出的字段,默认为read_only
    count = serializers.IntegerField(label='商品sku数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id', 'count', 'selected', 'name', 'default_image_url', 'price')


class CartDeleteSerializer(serializers.Serializer):
    """购物车删除指定商品序列化器"""
    sku_id = serializers.IntegerField(label='商品sku编号', min_value=1)

    def validate_sku_id(self, value):
        # 验证商品是否存在
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value


class CartSelectedSerializer(serializers.Serializer):
    """购物车全选/取消全选"""
    selected = serializers.BooleanField(label='商品是否勾选')
